package com.kgc.warehouse.bussness.service.impl;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kgc.warehouse.bussness.entity.Customer;
import com.kgc.warehouse.bussness.entity.Goods;
import com.kgc.warehouse.bussness.entity.Sales;
import com.kgc.warehouse.bussness.mapper.CustomerMapper;
import com.kgc.warehouse.bussness.mapper.GoodsMapper;
import com.kgc.warehouse.bussness.mapper.SalesMapper;
import com.kgc.warehouse.bussness.service.SalesService;
import com.kgc.warehouse.bussness.vo.SalesVO;
import com.kgc.warehouse.system.common.CodeMsg;
import com.kgc.warehouse.system.common.ResponseResult;
import com.kgc.warehouse.system.entity.User;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Date;

/**
* @author main
* @description 针对表【bus_sales】的数据库操作Service实现
* @createDate 2023-02-04 08:48:32
*/
@Service
@Transactional
public class SalesServiceImpl extends ServiceImpl<SalesMapper, Sales> implements SalesService{

    @Resource
    private SalesMapper salesMapper;
    @Resource
    private CustomerMapper customerMapper;

    @Resource
    private GoodsMapper goodsMapper;
    @Override
    public ResponseResult addSales(SalesVO salesVO, HttpSession session) {
        Goods goods = goodsMapper.selectById(salesVO.getGoodsid());
        if (salesVO.getNumber() < 50) {
            return new ResponseResult(CodeMsg.NUMBER_SALECOUNT);
        }
        if (salesVO.getNumber() > goods.getNumber()) {
            return new ResponseResult(CodeMsg.NUMBER_ISNULL);
        }

        //添加销售数据到销售表
        User user = (User) session.getAttribute("user");
        salesVO.setOperateperson(user.getName());
        salesVO.setSalestime(new Date());
        salesMapper.insert(salesVO);

        //更新商品库存信息

        goods.setNumber(goods.getNumber() - salesVO.getNumber());
        goodsMapper.updateById(goods);
        return new ResponseResult(CodeMsg.ADD_SUCCESS);
    }

    @Override
    public void deleteSales(Integer id) {

        Sales sales = salesMapper.selectById(id);
        Goods goods = goodsMapper.selectById(sales.getGoodsid());

        goods.setNumber(goods.getNumber()+sales.getNumber());
        salesMapper.deleteById(id);
        goodsMapper.updateById(goods);
    }

    @Override
    public void updateSales(SalesVO salesVO) {
        Goods goods = goodsMapper.selectById(salesVO.getGoodsid());
        Sales sales = salesMapper.selectById(salesVO.getId());
        goods.setNumber(goods.getNumber()+sales.getNumber()-salesVO.getNumber());
        salesMapper.updateById(salesVO);
        goodsMapper.updateById(goods);
    }
}




